package com.ds.infrastructure.audit.admin.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ds.infrastructure.audit.common.entity.Result;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/31
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {


    public static final Set<String> APPKEYS = ImmutableSet.of(
            "slnnh3f9gWdOBsJEixKGy2YTEkIIEbLW2aav2yqGJjvP1hKnCA2ZNdQyMxWRe50K",
            "ZHsdXIPYaSdH4lAoJ1qBYqipxgeczYf9ySbXHv7KupfwzbwUeprQ5LCR7KSSPyWU");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appkey = request.getHeader("APPKEY");

        if (StringUtils.isBlank(appkey)) {
            appkey = request.getParameter("APPKEY");
        }

        if (StringUtils.isBlank(appkey)) {
            appkey = request.getParameter("appkey");
        }
        if (appkey != null && APPKEYS.contains(appkey)) {
            return true;
        }
        Result result = new Result();
        result.setCode(401);
        responseResult(response, result);
        return false;
    }

    private void responseResult(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(result, SerializerFeature.WriteNullStringAsEmpty));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

